<?php
/**
 * Created by PhpStorm.
 * User: hans
 * Date: 16/6/13
 * Time: 下午5:35.
 */
namespace App\Helpers;

/**
 * Class SMS.
 */
class SMS
{
    /**
     * 发送验证码信息.
     *
     * @param string $mobile
     * @param string $type
     *
     * @return array
     */
    public function sendVerificationCode($mobile, $type)
    {
        //与最后一次发送间隔不少于60s
        $timeToLastSMS = $this->timeToLastSMS($mobile, 'reg');
        if ($timeToLastSMS < 60) {
            return ['message' => '验证码已发送,请耐心等待,'.(60 - $timeToLastSMS).'秒后可重新发送。'];
        }

        //随机验证码
        $code = rand(100000, 999999);

        //调用三方短信接口
        //SMS::send($mobile, $code, $type);

        //存储短信验证码
        $this->storeSMSCode($mobile, $code, $type);


        return ['message' => '短信验证码已发送!'];
    }

    /**
     * 检查验证码是否正确.
     *
     * @param string $mobile
     * @param string $code
     * @param string $type
     *
     * @return bool
     */
    public function validate($mobile, $code, $type)
    {
        $serverCode = app('redis')->get('sms:'.$type.':'.$mobile);

        return $serverCode == $code;
    }

    /**
     * 最后一次发送短信验证码的时间间隔.
     *
     * @param $mobile
     * @param $type
     *
     * @return bool
     */
    protected function timeToLastSMS($mobile, $type)
    {
        $ttl = app('redis')->ttl('sms:'.$type.':'.$mobile);

        return env('SMS_CODE_TTL', 300) - $ttl;
    }

    /**
     * 存储验证码
     *
     * @param string $mobile
     * @param string $code
     * @param string $type
     */
    protected function storeSMSCode($mobile, $code, $type)
    {
        $ttl = env('SMS_CODE_TTL', 300);
        app('redis')->setex('sms:'.$type.':'.$mobile, $ttl, $code);
    }

    public function noMock()
    {
        echo 'NO MOCK';
    }
}
